'''
Created on 2019年10月16日

@author: zxf
'''
import tushare as ts
import pandas as pd
import numpy as np
import talib
import wx
import os

   
class Mywin(wx.Frame):
     def __init__(self, parent, title):
         super(Mywin, self).__init__(parent, title = title)
         #全局变量
         global codeBox, starBox, endBox, macdFBox, macdSLBox,macdSIBox, buyBox, sellBox
         #在 窗口框架 上创建一个 面板
         panel = wx.Panel(self)
         font = wx.Font(9, wx.ROMAN, wx.NORMAL, wx.BOLD, False)
         fontbt = wx.Font(9, wx.ROMAN, wx.NORMAL, wx.BOLD, False)
         fontms = wx.Font(15, wx.ROMAN, wx.NORMAL, wx.NORMAL, False)
         font.SetPointSize(9)
 
         #创建 垂直尺寸管理器 : 用来管理接下来的 水平管理器 和 其他组件
         vbox = wx.BoxSizer(wx.VERTICAL)
        
          #创建 水平管理器 endDate、标签、普通编辑框(绑定 内容更改 事件) ， 并把后二者放到 endDate 上
         stockCode = wx.BoxSizer(wx.HORIZONTAL)
         codetext = wx.StaticText(panel, id = -1, size=(100,30), label = "股票代码：")
         #filepath3 = wx.TextCtrl(panel, size=(1024,30))
         codeBox = wx.TextCtrl(panel)
         #codeBox.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         stockCode.Add(codetext, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         stockCode.Add(codeBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
 
   #创建 水平管理器 endDate、标签、普通编辑框(绑定 内容更改 事件) ， 并把后二者放到 endDate 上
         starDate = wx.BoxSizer(wx.HORIZONTAL)
         stext = wx.StaticText(panel, id = -1, label = "开始时间：")
         starBox = wx.TextCtrl(panel)
         #self.st.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         starDate.Add(stext, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         starDate.Add(starBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
         #创建 水平管理器 endDate、标签、普通编辑框(绑定 内容更改 事件) ， 并把后二者放到 endDate 上
         endDate = wx.BoxSizer(wx.HORIZONTAL)
         endtext = wx.StaticText(panel, id = -1, label = "结束时间：")
         endBox = wx.TextCtrl(panel)
         #self.t1.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         endDate.Add(endtext, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         endDate.Add(endBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
         
         
         date = wx.BoxSizer(wx.HORIZONTAL)
         date.Add(starDate, flag=wx.LEFT , border=50)
         date.Add(endDate, flag=wx.RIGHT , border=50)
         
         
           #创建 水平管理器 endDate、标签、普通编辑框(绑定 内容更改 事件) ， 并把后二者放到 endDate 上
         macdF = wx.BoxSizer(wx.HORIZONTAL)
         macdFtext = wx.StaticText(panel, id = -1, label = "macdf：")
         macdFBox = wx.TextCtrl(panel)
         #self.t1.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         macdF.Add(macdFtext, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         macdF.Add(macdFBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
         
         
         macdSL = wx.BoxSizer(wx.HORIZONTAL)
         macdSLtext = wx.StaticText(panel, id = -1, label = "macdSL：")
         macdSLBox = wx.TextCtrl(panel)
         #self.t1.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         macdSL.Add(macdSLtext, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         macdSL.Add(macdSLBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
         
         
           
         macdSI = wx.BoxSizer(wx.HORIZONTAL)
         macdSItext = wx.StaticText(panel, id = -1, label = "macdSI：")
         macdSIBox = wx.TextCtrl(panel)
         #self.t1.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         macdSI.Add(macdSItext, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         macdSI.Add(macdSIBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
         
         
          
         macd = wx.BoxSizer(wx.HORIZONTAL)
         macd.Add(macdF, flag=wx.LEFT , border=50)
         macd.Add(macdSL , border=50)
         macd.Add(macdSI, flag=wx.RIGHT , border=50)
         
         
         buyP = wx.BoxSizer(wx.HORIZONTAL)
         stctext1 = wx.StaticText(panel, id = -1, label = "买参数：")
         buyBox = wx.TextCtrl(panel)
         #self.t1.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         buyP.Add(stctext1, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         buyP.Add(buyBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
         
         
         sellP = wx.BoxSizer(wx.HORIZONTAL)
         stctext1 = wx.StaticText(panel, id = -1, label = "卖参数：")
         sellBox = wx.TextCtrl(panel)
         #self.t1.Bind(wx.EVT_TEXT, self.OnKeyTyped)
         sellP.Add(stctext1, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
         sellP.Add(sellBox, proportion = 1, flag = wx.EXPAND|wx.ALL, border = 5)
       
 
         buySell = wx.BoxSizer(wx.HORIZONTAL)
         buySell.Add(buyP, flag=wx.LEFT , border=50)
         buySell.Add(sellP, flag=wx.RIGHT , border=50)
 
         hbox5 = wx.BoxSizer(wx.HORIZONTAL)
         #btn1:"RSA加密"
         btn1 = wx.Button(panel, label=u'查询', size=(110, 30))
         btn1.SetFont(font)
         hbox5.Add(btn1, flag=wx.LEFT , border=50)
         #btn2：“RSA解密”
         btn2 = wx.Button(panel, label=u'重置', size=(110, 30))
         btn2.SetFont(font)
         hbox5.Add(btn2, flag=wx.LEFT , border=50)    #两个按钮中间空间

        
         vbox.Add((-1, 15))  #预留15像素空白
 
       
 
         #将 endDate 、 hbox2 、hbox3 添加到 vbox 上
         vbox.Add(stockCode, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
         vbox.Add(date, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
         #vbox.Add(endDate, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
        
         vbox.Add(macd, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
         #vbox.Add(macdSL, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
         #vbox.Add(macdSI, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
         
         vbox.Add(buySell, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
         #vbox.Add(sellP, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
         vbox.Add(hbox5, flag=wx.ALIGN_CENTER_HORIZONTAL, border=30) #三个按钮右空间
 
        
         #设置 面板 panel 的尺寸管理器为 vbox
         panel.SetSizer(vbox)
 
         #调整 窗口框架 并显示
         self.SetSize((650,500))
         self.Center()
         self.Show()
         self.Fit()
         
         self.Bind(wx.EVT_BUTTON, self.encryptMessage, btn1)     #加密
         #self.Bind(wx.EVT_BUTTON, self.decryptMessage, btn2)     #解密
         
    
                  
     def encryptMessage(self, event):
         
           
            #进行加密算法，模式ECB模式，把叠加完16位的秘钥传进来
            #aes = AES.new(self.pad_key(Key), AES.MODE_ECB)
            #加密内容,此处需要将字符串转为字节
#codetext, stext, endtext, macdFtext, macdSLtext,macdSItext

            #Text = b'woshijiamineirong'
            #global Text
            tscode = codeBox.GetValue()
            starDate = starBox.GetValue()
            endDate = endBox.GetValue()
            macdF = macdFBox.GetValue()
            macdSL = macdSLBox.GetValue()
            macdSI = macdSIBox.GetValue()
            buy = buyBox.GetValue()
            sell = sellBox.GetValue()
            
            if  tscode == '':
                print("股票代码参数为null！")
                return
            if  starDate == '':
                print("开始时间参数为null！")
                return
            if  endDate == '':
                print("结束时间参数为null！")
                return
            
            
            
            self.computedResult(tscode,starDate,endDate,macdF,macdSL,macdSI,buy,sell)
            
    
             
 
 
     def computedResult(self,tscode,starDate,endDate,macdF,macdSL,macdSI,buy,sell):
        pro = ts.pro_api('a2c606601f02e667f405b59da6f34ecf6d00581d62a9e3cf831bb16b')
        
        # 使用ggplot样式，好看些
        #mpl..style.use("ggplot")
        # 获取上证指数数据
        #data = ts.get_k_data("000001", index=True, start="2019-01-01")
        ts_code='600575.SH'
        start_date='20180701'
        end_date='20191024'
        f =6
        s =12
        si =9
#       
        if  macdF != '':
            f = int(macdF)
        if  macdSL != '':
            s = int(macdSL)
             
        if  macdSI != '':
            si = int(macdSI)
        
        #print(type(macdF))
        
        data = pro.daily(ts_code=tscode, start_date=starDate, end_date=endDate)
        pd.set_option('display.max_columns', None)
        # 将date值转换为datetime类型，并且设置成index
        data.trade_date = pd.to_datetime(data.trade_date)
        data.index = data.trade_date
        
        # 计算MACD指标数据
        data["macd"], data["sigal"], data["hist"] = talib.MACD(data.close,fastperiod=f, slowperiod=s, signalperiod=si)
        # 计算移动平均线
        data["ma10"] = talib.MA(data.close, timeperiod=10)
        data["ma30"] = talib.MA(data.close, timeperiod=30)
        
        # 计算RSI
        #data["rsi"] = talib.RSI(data.close)
        
        # 计算MACD指标数据
        #data["macd"], data["sigal"], data["hist"] = talib.MACD(data.close)
        
        # 计算RSI
        #data["rsi"] = talib.RSI(data.close)
        
        #for date, row in data.iterrows():
            #print(row)
            
            
         #dataform 转成list   
        train_data = np.array(data)#np.ndarray()
        train_x_list=train_data.tolist()#list
        #print(train_x_list)
        #print(type(train_x_list))
        
        train_x_list.sort(reverse=False)
        #买点
        bu =0
        #卖点
        se =0
       
#       buy,sell
        if  buy != '':
            bu = int(buy)
        if  sell != '':
            se = int(sell)
             
       
        
        total =0
        a=0
        b=0
        buy=0.00 
        sell=0.00
        success_ratio = 0.00
        for i in range(1,len(train_x_list)-1):
            result=0.00
            #print(train_x_list[i])
            open = train_x_list[i][2]
            macd = float(train_x_list[i][11])
            sigal = float(train_x_list[i][12]) 
            close = train_x_list[i][5]
            
            open2 = train_x_list[i-1][2]
            macd2 = float(train_x_list[i-1][11])
            sigal2 = float(train_x_list[i-1][12]) 
            close2 = train_x_list[i-1][5]
            
            open3 = train_x_list[i+1][2]
            macd3 = float(train_x_list[i+1][11])
            sigal3 = float(train_x_list[i+1][12]) 
            close3 = train_x_list[i+1][5]
            
            if(macd2 != macd2):
                
                continue
           
            #macd sigal 买点 交叉点判断，前一天数值macd的值大于sigal2，后一天数据macd小于sigal
            if(macd3<sigal3 and macd2>sigal2):
                #buy=open
                buy = float(train_x_list[i+bu][2])
                print("买点：buy"+str(buy)+"第"+str(train_x_list[i+1][1]))
             #macd sigal 卖点  交叉点判断，前一天数值macd的值小于sigal2，后一天数据macd大于sigal   
            if(macd3>sigal3 and macd2<sigal2):
                #sell=open
                sell = float(train_x_list[i+se][2])
            if(buy != 0.00 and sell != 0.00):
                result = sell-buy
                if(result > 0):
                    b=b+1
                    
                print("卖点："+str(sell)+"开盘价差价："+str(result)+"第"+str(train_x_list[i][1]))
                buy = 0.00
                sell= 0.00
                a=a+1
               
            
            total = total + result
            if(a != 0):
                
                success_ratio = (b/a)*100
        #print(total)
        #print(success_ratio) 
        self.data_write(tscode,starDate,endDate,f,s,si,bu,se,total,success_ratio)
     
     #  将数据写入新文件
     def data_write(self,tscode,starDate,endDate,f,s,si,bu,se,total,success_ratio):
         result_list = [[tscode, starDate, endDate,f,s,si,bu,se,total,success_ratio]]
         columns = ["ts_code", "star_date", "end_date","macdF","macdSl","macdSI","buy","sell","total","success_ratio"]
         dt = pd.DataFrame(result_list, columns=columns)
         #dt.to_excel("result_xlsx.xlsx", index=0)
         #dt.to_csv("result_csv.csv", index=0)
         dt.to_csv('my_csv.csv', mode='a',header= 0,index=0,float_format='%.2f')
         #def OnKeyTyped(self, event):
#          print(event.GetString())
         self.data_read()

     def data_read(self):
         
         data = pd.read_csv('my_csv.csv')

         print(data)
 
     def OnEnterPressed(self, event):
         print("Enter Pressed")
 
     def OnMaxLen(self, event):
         print("Maximum length reached")
def main():
     app = wx.App()
     Mywin(None, "编辑框样例")
     app.MainLoop()
if __name__ == '__main__':
     main()





